import os
from typing import Annotated

from fastapi import APIRouter, Depends, Form, HTTPException, UploadFile, File
from sqlalchemy.orm import Session
from starlette.responses import JSONResponse

import models
from auth import pwd_context, get_current_active_user
from db import get_db
router = APIRouter(prefix="/api/user", tags=["用户"])
@router.put("/{user_id}")
def update_user(current_user: Annotated[models.User, Depends(get_current_active_user)],user_id: int, name: str=Form(...), phone: str=Form(...),  password: str=Form(...),
                db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if user_id is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    if name:
        user.name = name
    if phone:
        user.phone = phone
    if password:
        user.password = pwd_context.hash(password)
    db.commit()
    db.refresh(user)
    return {"message": "用户信息更新成功", "user": user}


@router.put("/user/upload-avatar")
def upload_avatar(user_id: int, file: UploadFile = File(...), db: Session = Depends(get_db),
                  current_user: models.User = Depends(get_current_active_user)):
    if current_user.id!= user_id:
        raise HTTPException(status_code=403, detail="不允许更新其他用户的头像")

    try:
        # 获取用户当前头像路径
        db_user = db.query(models.User).filter(models.User.id == user_id).first()
        old_avatar_path = db_user.avatar if db_user else None

        # 保存文件到服务器的某个位置
        file_location = f"uploads/{file.filename}"
        with open(file_location, "wb+") as file_object:
            file_object.write(file.file.read())

        # 更新数据库中的用户头像路径
        if db_user:
            # 删除旧头像文件（如果存在）
            if old_avatar_path and os.path.exists(old_avatar_path):
                os.remove(old_avatar_path)
            db_user.avatar = file_location
            db.add(db_user)
            db.commit()
            return JSONResponse(status_code=200, content={"message": "头像上传成功", "avatar_url": file_location})
        else:
            raise HTTPException(status_code=404, detail="用户未找到")
    except Exception as e:
        db.rollback()
        return JSONResponse(status_code=500, content={"message": "上传失败", "error": str(e)})